#!/usr/bin/env python3
"""
精确模拟refresh接口代码执行
"""
import sys
import os
import traceback
from datetime import datetime, timedelta

# 添加当前目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from sqlalchemy.orm import Session
from fastapi import HTTPException, status
from models import User, RefreshToken
from auth import AuthHandler, create_refresh_token_record, revoke_refresh_token
from database import get_db
from schemas import RefreshTokenRequest

class MockRefreshTokenRequest:
    """模拟RefreshTokenRequest"""
    def __init__(self, refresh_token: str):
        self.refresh_token = refresh_token

def simulate_refresh_token_endpoint():
    """精确模拟refresh token端点"""
    print("=== 精确模拟refresh token端点 ===")
    
    try:
        # 获取数据库会话
        db = next(get_db())
        
        # 获取最新token
        latest_token = db.query(RefreshToken).filter(
            RefreshToken.is_revoked == False
        ).order_by(RefreshToken.created_at.desc()).first()
        
        if not latest_token:
            print("❌ 没有找到有效的refresh token")
            return
            
        print(f"使用token: {latest_token.token[:50]}...")
        
        # 创建模拟请求数据
        refresh_data = MockRefreshTokenRequest(latest_token.token)
        
        print("开始模拟refresh端点执行...")
        
        try:
            # === refresh端点开始 ===
            
            # 1. 验证刷新令牌
            print("1. 验证刷新令牌...")
            payload = AuthHandler.verify_token(refresh_data.refresh_token)
            username: str = payload.get("sub")
            token_type: str = payload.get("type")
            
            print(f"   payload: {payload}")
            print(f"   username: {username}")
            print(f"   token_type: {token_type}")
            
            if username is None or token_type != "refresh":
                raise HTTPException(
                    status_code=status.HTTP_401_UNAUTHORIZED,
                    detail="无效的刷新令牌"
                )
            
            print("   ✓ 刷新令牌验证成功")
            
            # 2. 检查令牌是否被撤销
            print("2. 检查令牌是否被撤销...")
            refresh_token_record = db.query(RefreshToken).filter(
                RefreshToken.token == refresh_data.refresh_token,
                RefreshToken.is_revoked == False
            ).first()
            
            if not refresh_token_record:
                raise HTTPException(
                    status_code=status.HTTP_401_UNAUTHORIZED,
                    detail="令牌已失效"
                )
            
            print(f"   ✓ 找到token记录: ID={refresh_token_record.id}")
            
            # 3. 获取用户
            print("3. 获取用户...")
            user = db.query(User).filter(User.username == username).first()
            if not user:
                raise HTTPException(
                    status_code=status.HTTP_401_UNAUTHORIZED,
                    detail="用户不存在"
                )
            
            print(f"   ✓ 用户存在: {user.username} (状态: {user.status})")
            
            # 4. 创建新的访问令牌
            print("4. 创建新的访问令牌...")
            access_token_expires = timedelta(minutes=60)
            access_token = AuthHandler.create_access_token(
                data={"sub": user.username}, expires_delta=access_token_expires
            )
            print(f"   ✓ 新access token: {access_token[:50]}...")
            
            # 5. 创建新的刷新令牌
            print("5. 创建新的刷新令牌...")
            refresh_token_expires = timedelta(days=7)
            new_refresh_token = AuthHandler.create_refresh_token(
                data={"sub": user.username}, expires_delta=refresh_token_expires
            )
            print(f"   ✓ 新refresh token: {new_refresh_token[:50]}...")
            
            # 6. 撤销旧令牌，保存新令牌
            print("6. 撤销旧令牌...")
            revoke_refresh_token(db, refresh_data.refresh_token)
            print("   ✓ 旧token已撤销")
            
            print("7. 保存新令牌...")
            create_refresh_token_record(
                db, user.id, new_refresh_token,
                datetime.utcnow() + refresh_token_expires
            )
            print("   ✓ 新token已保存")
            
            # === refresh端点结束 ===
            
            # 返回结果
            result = {
                "access_token": access_token,
                "expires_in": 3600,
                "refresh_token": new_refresh_token
            }
            
            print("\n✅ Refresh端点执行成功！")
            print(f"返回结果: {result}")
            return result
            
        except HTTPException as e:
            print(f"❌ HTTP异常: {e.detail}")
            print(f"状态码: {e.status_code}")
            raise
        except Exception as e:
            print(f"❌ 未处理的异常: {e}")
            traceback.print_exc()
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="令牌刷新失败"
            )
        finally:
            db.close()
            
    except HTTPException as e:
        print(f"❌ 最终HTTP异常: {e.detail}")
        raise
    except Exception as e:
        print(f"❌ 最终异常: {e}")
        traceback.print_exc()
        raise

def test_fastapi_error_handling():
    """测试FastAPI错误处理"""
    print("\n=== 测试FastAPI错误处理 ===")
    
    # 测试HTTPException的detail信息
    try:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="令牌刷新失败"
        )
    except HTTPException as e:
        print(f"HTTPException详情: {e.detail}")
        print(f"HTTPException状态码: {e.status_code}")
    
    # 测试异常类型
    try:
        # 模拟数据库操作失败
        raise Exception("数据库操作失败")
    except Exception as e:
        print(f"模拟异常: {e}")

if __name__ == "__main__":
    test_fastapi_error_handling()
    
    try:
        result = simulate_refresh_token_endpoint()
        print(f"\n🎉 最终结果: {result}")
    except Exception as e:
        print(f"\n💥 最终失败: {e}")